package com.ruoyi.iot.dataprocessing.strategy;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.PrimaryKeyIdUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.customer.api.RemoteCustomerService;
import com.ruoyi.customer.api.domain.CustomerManagement;
import com.ruoyi.iot.dataprocessing.domain.SensorMessage;
import com.ruoyi.iot.dataprocessing.enums.DataAssemblyEnum;
import com.ruoyi.iot.dataprocessing.enums.HealthTopicEnum;
import net.dreamlu.iot.mqtt.spring.client.MqttClientTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

@Component
public class WatchHander extends SensorMessageHandlerService{
    @Autowired
    private RemoteCustomerService customerService;
    @Autowired
    private MqttClientTemplate client;

    @Override
    public DataAssemblyEnum getDataAssemblyEnum() {
        return DataAssemblyEnum.WATCH;
    }

    public SensorMessage messageHandle(byte[] payload) {
        JSONObject jsonObject = JSONObject.parseObject(new String(payload));
        JSONObject data = jsonObject.getJSONObject("data");
        if(data.getDouble("bloodGlucose").equals(0.0d)&&data.getJSONArray("oxygens").getBigInteger(0).equals(0)){
            throw new ServiceException("该数据为空数据");
        }
        SensorMessage sensorMessage = new SensorMessage();
        R<CustomerManagement> phoneNumber = customerService.getInfoByPhoneNumber(jsonObject.getString("phoneNumber"), SecurityConstants.INNER);
        if (StringUtils.isNull(phoneNumber) || StringUtils.isNull(phoneNumber.getData())){
            throw new ServiceException("该条数据的所属用户不存在，电话号码为："+jsonObject.getString("phoneNumber"));
        }
        sensorMessage.setCustomerId(phoneNumber.getData().getId());
        sensorMessage.setId(PrimaryKeyIdUtils.getSysIdWorker().nextId());
        sensorMessage.setDeviceType(jsonObject.getIntValue("type"));
        sensorMessage.setDeviceNo(jsonObject.getString("mac"));
        sensorMessage.setMessage(payload);
        String mTimeStr = data.getString("mTime");
        Date date = DateUtils.parseDate(mTimeStr);
        // 创建一个 Calendar 实例并设置时间为原始时间
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // 在原始时间基础上加上5分钟
        calendar.add(Calendar.MINUTE, 5);
        // 获取加了5分钟后的时间
        Date fiveMinutesLater = calendar.getTime();
        sensorMessage.setTsStart(date);
        sensorMessage.setTsEnd(fiveMinutesLater);
        sensorMessage.setCreateTime(DateUtils.getNowDate());
        return sensorMessage;
    }

    @Override
    public void push(Integer type,Long customerId,byte[] payload) {
        JSONObject jsonObject = JSONObject.parseObject(new String(payload));
        JSONObject data = jsonObject.getJSONObject("data");
        JSONArray oxygens = data.getJSONArray("oxygens");
        JSONArray ppgs = data.getJSONArray("ppgs");
        String string = oxygens.getString(4);
        String string2 = oxygens.getString(0);
        String string3 = ppgs.getString(4);
        String string4 = ppgs.getString(0);

        push1("0".equals(string)?string2:string,HealthTopicEnum.OXYGEN.getTopic() + customerId);
        push1("0".equals(string3)?string4:string,HealthTopicEnum.HEART_RATE.getTopic() + customerId);
        push1(data.getString("bloodGlucose"),HealthTopicEnum.GLUCOSE.getTopic() + customerId);
        push2(data,customerId);
    }

    public void push1(String data,String  topic){
        if("0".equals(data)||"0.0".equals(data)){
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("value",data);
        client.publish(topic, JSONObject.toJSONString(map).getBytes(StandardCharsets.UTF_8));
    }
    public void push2(JSONObject data, Long customerId){
        if("0".equals(data.getString("highValue"))){
            return;
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("systolic",data.getString("highValue"));
        map.put("diastolic",data.getString("lowValue"));
        client.publish(HealthTopicEnum.BLOOD_PRESSURE.getTopic() + customerId, JSONObject.toJSONString(map).getBytes(StandardCharsets.UTF_8));
    }

}
